package cc.rengu.igas.bsps.core.realize.impl;


import cc.rengu.igas.bsps.common.dao.*;
import cc.rengu.igas.bsps.common.dao.impl.*;
import cc.rengu.igas.bsps.common.entity.*;
import cc.rengu.igas.bsps.common.enums.RespCodeEnum;
import cc.rengu.igas.bsps.core.realize.PublicDealService;
import cc.rengu.igas.share.common.enums.SettleAcctTypeEnum;
import cc.rengu.oltp.service.model.BizException;
import cc.rengu.oltp.utility.util.DateUtil;
import cc.rengu.oltp.utility.util.StringUtil;
import cc.rengu.utility.log.RgLog;
import cc.rengu.utility.log.RgLogger;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;


/**
 * 商户相关的业务实现组件
 *
 * @author Daniel
 */
public class PublicDealServiceImpl implements PublicDealService {
    private final RgLogger rglog = RgLog.getLogger(this.getClass().getName());

    @Override
    public Boolean checkUserOpAuth(String instId, String mchntNo, String userId, String opUserId) throws Exception {
        boolean authFlag = false;
        /*获取用户角色信息*/
        BspsMchntBindInfoMapper bspsMchntBindInfoMapper = new BspsMchntBindInfoMapperImpl();
        MchntBindInfo mchntBindInfo = bspsMchntBindInfoMapper.selectBspsMchntBindInfoListByUserIdAndMchntNo(instId, userId, mchntNo);
        if (null != mchntBindInfo) {
            if ("00".equals(mchntBindInfo.getBindUserRole())) {
                /*  商户法人角色 ，查询法人商户及其门店中是否有被操作人的绑定信息数据 */
                List<MchntBindInfo> mchntBindUserInfoList = bspsMchntBindInfoMapper.selectBspsMchntBindInfoListByMchntNoAndChainMchntNo(instId, opUserId, mchntNo);
                if (null != mchntBindUserInfoList && !mchntBindUserInfoList.isEmpty()) {
                    authFlag = true;
                }
            } else if ("01".equals(mchntBindInfo.getBindUserRole())) {
                /* 门店店长角色，查询该门店下是否有被操作人的绑定信息数据*/
                MchntBindInfo mchntBindUserInfo = bspsMchntBindInfoMapper.selectBspsMchntBindInfoListByUserIdAndMchntNo(instId, opUserId, mchntNo);
                if (null != mchntBindUserInfo) {
                    authFlag = true;
                }
            } else if ("02".equals(mchntBindInfo.getBindUserRole()) && userId.equals(opUserId)) {
                /* 商户收银员角色且操作自己的数据*/
                authFlag = true;
            } else {
                rglog.error("用户角色<{}>非法人、店长或收银员", mchntBindInfo.getBindUserRole());
                throw new BizException(RespCodeEnum.GET_USER_ROLE_INFO_ERROR.getRespCode(), RespCodeEnum.GET_USER_ROLE_INFO_ERROR.getRespDesc());
            }
        } else {
            rglog.error("根据机构标识<{}>用户标识<{}>及商户号<{}>获取用户角色信息失败!", instId, userId, mchntNo);
            throw new BizException(RespCodeEnum.GET_USER_ROLE_INFO_ERROR.getRespCode(), RespCodeEnum.GET_USER_ROLE_INFO_ERROR.getRespDesc());
        }
        return authFlag;
    }

    /**
     * 获取机构内部户
     * 提现/D0（本行）： 本行渠道户->商户结算账户
     * 提现/D0（他行）： 本行垫资户->商户结算账户
     * 充值（本行）：    消费卡号->本行渠道户
     *
     * @param instId     机构号
     * @param settleAcct 科目/账号标识  SettleAcctTypeEnum （待清算款，应付商户款，..）
     * @throws Exception
     */
    @Override
    public RoleAcctInfo getInnerAccountByCondition(String instId, SettleAcctTypeEnum settleAcct) throws Exception {
        RoleAcctInfoMapper roleAcctInfoMapper = new RoleAcctInfoMapperImpl();
        RoleAcctInfo roleAcctInfo = roleAcctInfoMapper.selectBankRoleAcctInfoBySettleAcctId(instId, settleAcct.getSettleAcct());
        return roleAcctInfo;
    }

    @Override
    public void checkMchntBlackInfo(String instId, String mchntNo) throws Exception {
        /*对商户进行黑名单检查*/
        MchntBlackListMapper mchntBlackListMapper = new MchntBlackListMapperImpl();
        List<MchntBlackListInfo> mchntBlackListInfoList = mchntBlackListMapper.selectBompMchntBlackListInfoByInstIdMchntNo(instId, mchntNo);
        if (!CollectionUtils.isEmpty(mchntBlackListInfoList)) {
            mchntBlackListInfoList = mchntBlackListInfoList.stream().filter(item -> "01".equals(item.getValidStatus())).collect(Collectors.toList());
            if (!CollectionUtils.isEmpty(mchntBlackListInfoList)) {
                for (MchntBlackListInfo mchntBlackListInfo : mchntBlackListInfoList) {
                    if (mchntBlackListInfo.getValidDate() == null ||
                            DateUtil.compareDate(DateUtil.getCurrentDate(), mchntBlackListInfo.getValidDate()) < 0) {
                        rglog.info("机构:{}的商户{}被列入黑名单。", instId, mchntNo);
                        throw new BizException(RespCodeEnum.MCHNT_INBLACK_ERROR.getRespCode(), RespCodeEnum.MCHNT_INBLACK_ERROR.getRespDesc());
                    }
                }
            }
        }

    }

    @Override
    public List<MchntBindInfo> mchntCashierListQuery(String instId, String mchntNo, String userId) throws Exception {
        List<MchntBindInfo> mchntBindInfoList = new ArrayList<>();
        BspsMchntBindInfoMapper bspsMchntBindInfoMapper = new BspsMchntBindInfoMapperImpl();
        if (StringUtil.isEmptyOrNull(userId)) {
            mchntBindInfoList = bspsMchntBindInfoMapper.selectBspsMchntBindInfoListByMchntNoAndChainMchntNo(instId, null, mchntNo);
        } else {
            //判断用户角色是否允许查询
            MchntBindInfo mchntBindInfo = bspsMchntBindInfoMapper.selectBspsMchntBindInfoListByUserIdAndMchntNo(instId, userId, mchntNo);
            if (null == mchntBindInfo) {
                rglog.error("获取用户角色信息失败,mchntNo:<{}>,userId:<{}>", mchntNo, userId);
                throw new BizException(RespCodeEnum.GET_USER_ROLE_INFO_ERROR.getRespCode(), RespCodeEnum.GET_USER_ROLE_INFO_ERROR.getRespDesc());
            }
            String bindUerRole = mchntBindInfo.getBindUserRole();
            /**
             * 判断操作用户角色
             * 1-若为商户法人则根据商户号和连锁商户号过滤
             * 2-若为店长则根据商户号过滤
             * 3-若为收银员则是自身
             */
            //1根据传入商户号作为商户号（MCHNT_NO），连锁门店号（CHAIN_MCHNT_NO）查询商户绑定关系表T_S_MCHNT_BIND_INFO，获取该商户和旗下门店的收银员信息；
            if ("00".equals(bindUerRole) || "01".equals(bindUerRole)) {
                //00-商户法人,01-店长
                //商户法人 允许查询所有收银员信息  根据机构号与商户号与连锁门店号查询
                mchntBindInfoList = bspsMchntBindInfoMapper.selectBspsMchntBindInfoListByMchntNoAndChainMchntNo(instId, null, mchntNo);
            } else if ("02".equals(bindUerRole)) {//02-收银员
                mchntBindInfoList.add(mchntBindInfo);
            }
        }

        return mchntBindInfoList;
    }

    @Override
    /**
     * 根据商户组别编码查询商户组别信息
     * */
    public String getManageScope(String management) throws Exception {
        BspsMerGroupInfoMapper bspsMerGroupInfoMapper = new BspsMerGroupMapperImpl();
        MerGroupInfo merGroupInfo = bspsMerGroupInfoMapper.selectBspsMerGroupInfoByGroupNo(management);
        if (null == merGroupInfo || StringUtil.isEmptyOrNull(merGroupInfo.getGrpDesc())) {
            rglog.error("获取商户组别信息失败！");
            return "";
        }
        return merGroupInfo.getGrpDesc();
    }

    @Override
    public String getRegionName(String regionCode) throws Exception {
        BspsRegionInfoMapper bspsRegionInfoMapper = new BspsRegionInfoMapperImpl();
        RegionInfo regionInfo = bspsRegionInfoMapper.selectBspsRegionInfoByPrimaryKey(regionCode);
        if (null == regionInfo) {
            rglog.error("获取行政区域信息失败！");
            return "";
        }
        return regionInfo.getRegionName();
    }

    @Override
    public Boolean checkUserOpAuthTransInfoQuery(String instId, String mchntNo, String userId, String opUserId) throws Exception {
        boolean authFlag = false;
        /*获取用户角色信息*/
        BspsMchntBindInfoMapper bspsMchntBindInfoMapper = new BspsMchntBindInfoMapperImpl();
        MchntBindInfo mchntBindInfo = bspsMchntBindInfoMapper.selectBspsMchntBindInfoListByUserIdAndMchntNo(instId, userId, mchntNo);
        if (null != mchntBindInfo) {
            if ("00".equals(mchntBindInfo.getBindUserRole())) {
                /*  商户法人角色 ，查询法人商户及其门店中是否有被操作人的绑定信息数据 */
                List<MchntBindInfo> mchntBindUserInfoList = bspsMchntBindInfoMapper.selectBspsMchntBindInfoListByMchntNoAndChainMchntNo(instId, opUserId, mchntNo);
                if (null != mchntBindUserInfoList && !mchntBindUserInfoList.isEmpty()) {
                    authFlag = true;
                }
            } else if ("01".equals(mchntBindInfo.getBindUserRole())) {
                /* 门店店长角色，查询该门店下是否有被操作人的绑定信息数据*/
                MchntBindInfo mchntBindUserInfo = bspsMchntBindInfoMapper.selectBspsMchntBindInfoListByUserIdAndMchntNo(instId, opUserId, mchntNo);
                if (null != mchntBindUserInfo) {
                    authFlag = true;
                }
            } else if ("02".equals(mchntBindInfo.getBindUserRole()) && userId.equals(opUserId)) {
                authFlag = false;
            } else {
                rglog.error("用户角色<{}>非法人、店长或收银员", mchntBindInfo.getBindUserRole());
                throw new BizException(RespCodeEnum.GET_USER_ROLE_INFO_ERROR.getRespCode(), RespCodeEnum.GET_USER_ROLE_INFO_ERROR.getRespDesc());
            }
        } else {
            rglog.error("根据机构标识<{}>用户标识<{}>及商户号<{}>获取用户角色信息失败!", instId, userId, mchntNo);
            throw new BizException(RespCodeEnum.GET_USER_ROLE_INFO_ERROR.getRespCode(), RespCodeEnum.GET_USER_ROLE_INFO_ERROR.getRespDesc());
        }
        return authFlag;
    }
}
